package view.drawing;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;

/**
 * ImageLibrary exists as a centralized loader for Images. It is a simple class that
 * maintains a list of references to previously loaded images in the event they have
 * already been loaded by a previous request to <code>getImage().</code>
 * 
 * 
 * @author matt
 *
 */
public class ImageLibrary {
	
	private Map<String, Image> mImageMap;
	
	private static ImageLibrary mInstance = null;
	
	static {
		mInstance = new ImageLibrary();
	}

	
	private ImageLibrary() {
		mImageMap = new HashMap<String, Image>();
	}
	
	/**
	 * Attemps to load an image from the file specified. If successful, the Image
	 * is returned. If an exception occurs, this operation may return NULL.
	 * 
	 * Values returned from calls to <code>getImage()</code> should always be
	 * null-checked.
	 * 
	 * @param filepath		String		The file path to the image.
	 * @return				Image		The image at that location, or null.
	 */
	public Image getImage(String filepath) {
		
		return (getImage(new File(filepath)));
	}
	
	public Image getImage(File file) {
		// Check if we already have a key for it
		if (mImageMap.containsKey(file.getAbsolutePath())) {
			Image img = mImageMap.get(file.getAbsolutePath());
			
			// If the image is null, we don't want to return it and we will try to load it again.
			if (img != null) {
				return (img);
			}
		}
		
		try {
			// Read the file from the path
			BufferedImage image = ImageIO.read(file);
			
			// Store the image in our map for future retreival
			mImageMap.put(file.getAbsolutePath(), image);
			
			return (image);
		}
		catch (IOException ex) {
			System.err.format("ImageLibrary::getImage() : Error loading image from path '%s'\n", file.getAbsolutePath());
			return (null);
		}
	}
	
	public static ImageLibrary getInstance() {
		return (mInstance);
	}
}
